package Domostroy::Data;
use strict;
use strict 'refs';
use warnings;
use utf8;
use v5.10;

# Модуль для получения данных#

require Exporter;
use vars qw($VERSION @ISA );

@ISA=qw(Exporter);
$VERSION = '0.02';

use CGI;
use CGI::Carp qw(fatalsToBrowser);
use Domostroy::Config;

my $env = new Domostroy::Config->env();
#my $dbh = DBI->connect($env->{'DBH'});

sub new {
	my ($class, %args) = @_;
	my $self = {};
	bless $self, ref $class || $class;
	return $self;
}

sub getData {
	my ($self) = @_;
	return $env;
}

sub handlerHashToSQL {
	my ($self,%data) = @_;
	my $sql; my $fields; my $values; my $where;
	my $oper = $data{'oper'}; 
	print `rm -f /tmp/handlerDataToSQL.log`;
	while (my ($k,$v) = each %data ) {
		print `echo "Step1: $k = $v" >> /tmp/handlerDataToSQL.log`;
	}
	if ( $oper eq "add" ) {
		$sql = "insert into $data{'table'}";  delete $data{'table'};
		while ( my ($key,$val) = each %data ){
			if ( $val ) {
				$fields .= qq~$key,~; $values .= qq~'$val',~;
			}
		}
		$fields =~ s/\,$//; $values =~ s/\,$//;
		$sql = qq~$sql ($fields) values ($values)~;
		
	} elsif ( $oper eq "edit" ) {
		
		$sql = "update $data{'table'} set "; 
		if ( $data{'condition'} ) {
			$where = "where $data{'condition'}"; 
		}
		while ( my ($key,$val) = each %data ){
			$fields .= qq~$key = '$val',~;
		}
		$fields =~ s/\,$//;
		$sql = qq~$sql $fields $where~;
		
	} elsif ( $oper eq "del" ) {
		
		$sql = "delete from $data{'table'} "; 
		
		if ( $data{'condition'} ) {
			$where = "where $data{'condition'}"; 
			$sql = qq~$sql $where~;
		} 
		
	} elsif ( $oper eq "select" ) {
		if ( $data{'that'} ) {
			$sql = qq~select $data{'that'} from $data{'table'}~;
		} else {
			$sql = qq~select * from $data{'table'}~;
		}
		if ( $data{'condition'} ) {
			$where = "where $data{'condition'}"; 
			$sql = qq~$sql $where~;
		}
	}
	print `echo "Step2: $sql" >> /tmp/handlerDataToSQL.log`;
	return $sql;
}


1;